package com.shi.controller;

import com.shi.annotation.Auth;
import com.shi.common.Result;
import com.shi.properties.SysProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Api(tags = "文件上传和下载")
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private SysProperties sysProperties;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    @Auth
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        File dir = new File(getFileDir(originalFilename));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String newFileName = UUID.randomUUID() + originalFilename.substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(dir, newFileName));
        return Result.ok(newFileName);
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{fileName}")
    @Auth
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        String dir = getFileDir(fileName);
        String fullName = dir + fileName;
        try (
                ServletOutputStream outputStream = response.getOutputStream();
                FileInputStream fileInputStream = new FileInputStream(fullName);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)
        ) {
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getFileDir(String fileName) {
        String type = MediaTypeFactory.getMediaType(fileName).get().getType();
        String dir;
        if ("video".equals(type)) {
            dir = new File(sysProperties.getVideoDir()).getAbsolutePath();
        } else {
            dir = new File(sysProperties.getPicDir()).getAbsolutePath();
        }
        return dir.endsWith(File.separator) ? dir : dir + File.separator;
    }
}
